<!-- 页面标注 -->
<html>
	<head>
		 <meta charset="UTF-8" />
		 <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		 <!-- <script src="http://api.tianditu.gov.cn/api?v=4.0&tk=e1055c36e70588515b90f03a62e02c09" type="text/javascript"></script> -->
		 <script src="http://lbs.tianditu.gov.cn/js/lib/d3/d3.min.js" charset="utf-8"></script>
		 <script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/D3SvgOverlay.js"></script>
		 <script src="http://lbs.tianditu.gov.cn/api/js4.0/opensource/openlibrary/CarTrack.js"></script>
		 <title>主体标注</title>
		 <style>
			 body{
				 padding: 0px;
				 margin-left: 0px;
			 }
			 #map {
				 width: 100%;
				 height: 100%;
			 }
			 .point {
			 	position: fixed;
			 	z-index: 10;
			 	bottom: 160px;
			 	left: 20px;
			 	background-color: #FFFFFF;
			 	width: 50px;
			 	height: 50px;
			 	display: flex;
			 	align-items: center;
			 	justify-content: center;
			 }
			 
			 .bottom-content{
			 	position: fixed;
			 	bottom: 0px;
			 	height: 130px;
			 	width: 100%;
			 	padding-top: 20px;
				background-color: #fff;
				z-index: 20;
			 }
			 .point-item{
			 	padding: 5px 10px;
			 	display: flex;
			 	flex-direction: row;
			 	justify-content: flex-start;
			 	align-items: center;
			 }
			 .point-icon{
			 	width: 25px;
			 	height: 25px;
			 }
			 .point-text{
			 	color: black;
			 	font-size: 14px;
			 	margin-left: 5px;
			 }
			 .point-input{
			 	width: 500rpx;
			 	height: 40px;
			 	margin-left: 10px;
			 	margin-right: 10px;
			 	padding: 0px 5px ;
			 	border: 1px solid #e8e8e7;
			 } 
			 .navigator{
				 top:0px;
				 display: flex;
				 flex-direction: row;
				 justify-content: space-between;
				 align-items: center;
				 height: 60px;
				 position: fixed;
				 z-index:80;
				 width: calc(100% - 20px);
				 background-image: url('img/inspectBg.png');
				 background-size: 100% 100%;
				 padding: 0px 10px;
				 flex:1;
			 }
			 .navigator-left{
				 width: 20px;
				 height: 20px;
			 }
			 .navigator-title{
				 color: #FFFFFF;
				 font-size: 20px;
			 }
		 </style>
	</head>
	<body >    
		<div style="position: absolute;z-index:2" id="map"></div>
	</body>   
	<script type="text/javascript" src="./js/jquery.min.js"></script>
	<script type="text/javascript" src="./js/uni.webview.1.5.6.js"></script> 
	<script type="text/javascript" src="./js/map-util.js"></script>  
	<!-- <script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script> -->
	<script type="text/javascript"> 
		//var vConsole = new window.VConsole();
		
		function initScript(){ 
			$.get("https://111.33.173.50:8081/base/getTianKey",{},function(res){
				console.log("res",res);
			    var scriptS = document.createElement("script");
				scriptS.src = 'http://api.tianditu.gov.cn/api?v=4.0&tk='+res.data;
				 scriptS.onload = function () {
					initMap()  
				}; 
				
				scriptS.onerror = function () {
				    console.error('脚本加载失败');
				};
				
				document.head.appendChild(scriptS);
			})
		 }
		
		
		var map = null;// 地图实例 
		var int = null; 
		//初始化地图
		 document.addEventListener("DOMContentLoaded", function() {
		     // 在这里编写你想要在页面加载完毕后执行的代码
			initScript();
		 });
		 
		function initMap(){
			setTimeout(function(){
				// 初始化地图
				map =  new T.Map('map'); 
				map.centerAndZoom(new T.LngLat(117.201509, 39.085318), 12);   
				uni.postMessage({
					data:{type:'loadCompanyList'}
				})
			},500);
		}  
		var drivingNumber = 0;
		var lngLatList = [];//按照加入获取路由的顺序进行存储
		var polylinePointSortArr = []; //先将每组坐标存成起来,然后再通过开始坐标和结束坐标排序
		var _CarTrack = null; //车辆路径对象 
		var _line = null; 
		var _polylineArrowTool = null; 
		/**
		 * 统一处理所有企业路线
		 * @param {Object} points 所有坐标
		 */  
		function makePoints(points){ 
			if(points == '' || points == null){ 
				uni.postMessage({
					data:{type:'toast',message:'坐标数据为空!',icon:'error'}
				})
				setTimeout(function(){
					uni.postMessage({
						data:{type:'back'}
					})
				},1000)
				return;
			} 
			var pointArr = [];//存储nvue页面传递的数组 
			var pointsJSON = [];//存储nvue页面传递的企业id
			lngLatList = [];//执行的时候重置
			polylinePointSortArr = []; //执行的时候重置
			if(_CarTrack){
				_CarTrack.stop();
				_CarTrack.clear(); 
			} 
			//调试
	      	//console.log("points",points);
			pointsJSON = JSON.parse(points);
			//console.log("pointsJSON",pointsJSON);
			for (var i = 0; i < pointsJSON.length; i++) {
				pointArr.push(pointsJSON[i].lngLat); 
			}
			
			 uni.postMessage({
				data:{type:'loading',message:'正在获取路线信息'}
			}) 
			try{ 
				var lngLatArr = [];//存储对像LngLat
				//创建marker 
				for (var i = 0; i < pointArr.length; i++) { 
					 let lngLat= pointArr[i].split(","); 
					let  lngLatEnd = new T.LngLat(lngLat[0], lngLat[1]); 
					lngLatArr.push(lngLatEnd);  
				}  
				//清空涂层
				map.clearLayers();
				//清空之前的marker
				map.clearOverLays();
				//创建marker图标
				createStartMarker(lngLatArr,pointsJSON,function(){
					//地图中心移动到第一个坐标
					map.panTo(lngLatArr[0]);
				});
				//路线规划 
				generatorRoute(lngLatArr);
			}catch(e){
				console.error(e);
				uni.postMessage({
					data:{type:'toast',message:'线路规划失败',icon:'error'}
				})
			}
		}
		
		//添加起始点
		function createStartMarker(lngLatArr,pointsJSON,callback) {
			for (var i = 0; i < lngLatArr.length; i++) {  
				if(pointsJSON[i] == null){
					continue;
				}
				//创建标注对象
				var marker = new T.Marker(lngLatArr[i],{
					companyId: pointsJSON[i].companyId == '' ? null : pointsJSON[i].companyId ,
					companyName: pointsJSON[i].companyName
				}); 
				marker.addEventListener("click",function(e){ 
					var companyId = e.target.options.companyId;
					if(companyId == null || companyId == ''){
						uni.postMessage({
							data:{type:'toast',message: "该点位是当前坐标",icon:'error'}
						})
						return;
					}
					uni.postMessage({
						data:{type:'toCompanyInfo',companyId: companyId}
					})
				})
				//向地图上添加标注
				map.addOverLay(marker);
				// 添加label
				var label = new T.Label({
					text: pointsJSON[i].companyName,
					position: lngLatArr[i]
				})
				map.addOverLay(label);
			}
			if(callback){
				callback()
			}
		}
		
		
		/**
		 * 计算每组坐标路由
		 * @param {Object} lngLatArr
		 */
		function generatorRoute(lngLatArr){ 
			 try{
				for (var i = 0; i < lngLatArr.length - 1; i++) { 
					let drivingRoute =  new T.DrivingRoute(map,{
						 policy: 0 
					 }); 
					lngLatList.push(lngLatArr[i]);
					drivingRoute.search(lngLatArr[i],lngLatArr[i+1]);
					drivingRoute.clearResults();
					drivingRoute.setSearchCompleteCallback(function(result){
						var routePointArr = result.results.routelatlon.split(";");
						if(routePointArr[routePointArr.length - 1] == ''){
							//split之后有的最后一组数据是空的,这里去除一下
							routePointArr.splice(routePointArr.length - 1,1);
						}
						polylinePointSortArr.push(routePointArr);
						drivingNumber  = drivingNumber + 1; 
					}); 
				}
				//监听路线获取完成,执行后面业务
				lisentsPointComplate(lngLatArr); 
			 }catch(e){
				console.error(e);
			 }
		}
		 
		 /**
		  * 监听路线全部获取完成 
		  * @param {Object} lngLatArr
		  */
		function lisentsPointComplate(lngLatArr){ 
			let interval = setInterval(() => { 
			  // 判断当前数值是否等于目标数值 
			  if (drivingNumber === lngLatArr.length -1) { 
				  //重置次数 
				  drivingNumber  = 0;
				//最后一组获取完信息之后再画出路线
			    clearInterval(interval);
				console.log("画出路线");
				uni.postMessage({
					data:{type:'closeLoading'}
				}) 
				//console.log('开始排序')
				let  polylinePointArr  = sortRoute(); 
				//createPolyline(polylinePointArr); //画出线路
				createCarLine(polylinePointArr); //小汽车行驶
			    // 清除定时器
			  }
			}, 500); // 每隔1秒检查一次
		}
	 
		/**
		 * 由于路线信息是异步返回,所以返回的顺序不一定是本身传入的顺序,所以这里根据每组的第一个坐标和最后一个坐标进行排序
		 */
		 function sortRoute(){
			let  polylinePointArr =[];
			let  polylinePointArrResult =[];
			 //对多组路线坐标进行排序
			 for (var i = 0; i < lngLatList.length; i++) {
			 	for (var n = 0; n < polylinePointSortArr.length; n++) {
					//console.log(polylinePointSortArr[n][0] + '------'+ (lngLatList[i].lng +","+lngLatList[i].lat)+"="+(polylinePointSortArr[n][0] == (lngLatList[i].lng +","+lngLatList[i].lat)))
			 		if(polylinePointSortArr[n][0] == (lngLatList[i].lng +","+lngLatList[i].lat)){
						polylinePointArr.push(polylinePointSortArr[n]);
						break;
					}
			 	}
			 } 
			 console.log(polylinePointArr);
			 //对数组拆分
			 for (var y = 0; y < polylinePointArr.length ; y++) {
				//console.log(polylinePointArr[y][0]+"----"+polylinePointArr[y][polylinePointArr[y].length -1])
			 	if(polylinePointArr[y] == ''){
			 		continue;
			 	}
			 	for (var i = 0; i < polylinePointArr[y].length; i++) {
			 		var	routePoint  = polylinePointArr[y][i].split(',');
			 		if(routePoint == ''){
			 			continue;
			 		}
			 		polylinePointArrResult.push(new T.LngLat(routePoint[0], routePoint[1]) ); 
			 	} 
			 }
			 return polylinePointArrResult;
		 }
		
		/**
		 * 创建小汽车路线
		 * @param {Object} routesArr
		 */
 		 function createCarLine(routesArr){ 
			console.log("生成汽车路线 ")
			_CarTrack = new T.CarTrack(map, {
				interval: 20,
				speed: 40,
				dynamicLine: false,
				Datas: routesArr,
				polylinestyle: {color: "#2C64A7", width: 5, opacity: 0.9}
			});
		} 
		function startCar(){
			console.log("开始")
			_CarTrack.start();
		}
		function pauseCar(){
			console.log("暂停")
			_CarTrack.pause();
		}
		function stopCar(){
			console.log("结束")
			_CarTrack.stop();
		} 
        //添加路线的线
        function createPolyline(routesArr) {
			//线路
			_line = new T.Polyline(routesArr,{
                color: "blue", weight: 4, opacity: 0.9
            }); 
			map.addOverLay(_line); 
        }
	
		function bacPage(){
			console.log('返回')
			uni.postMessage({
				data:{type:'back'}
			})
		}
	</script>
</html>